package com.generalbackend.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.generalbackend.common.constants.Constants;
import com.generalbackend.common.util.ClientUtil;
import com.generalbackend.role.service.IPermissionService;
import com.generalbackend.role.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义登录逻辑
 * @author tim.xie
 * @date 2021/11/30 10:05
 */
@Service
public class SecurityUserServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.generalbackend.common.model.entity.User user = userService.login(null, username);
        String password = user.getPassword();
        JSONArray permission = permissionService.getPermissionByUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permission.toJavaList(String.class).stream().forEach(bean -> {
            if(bean != null) {
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(bean);
                grantedAuthorities.add(simpleGrantedAuthority);
            }
        });
        User userDetails = new User(username, password, grantedAuthorities);
        JSONObject json = packageSession(user, ClientUtil.getSession());
        ClientUtil.getRequest().setAttribute("loginMessage", json);
        return userDetails;
    }

    /**
     * 封装session
     * @param user
     * @param session
     * @return
     */
    public JSONObject packageSession(com.generalbackend.common.model.entity.User user, HttpSession session) {
        JSONObject json = new JSONObject();
        user.setPassword("");
        session.setAttribute(Constants.USER_INFO, user);
        session.setAttribute(Constants.USER_ID, user.getId());
        session.setAttribute(Constants.MENUS, permissionService.getPermissionByUserId(user.getId()));
        json.put(Constants.USER_INFO, session.getAttribute(Constants.USER_INFO));
        json.put(Constants.MENUS, session.getAttribute(Constants.MENUS));
        return json;
    }

}
